const importLazy = require('import-lazy')(require);
const inquirer = require('inquirer');

const Okapi = importLazy('../okapi/okapiRepository.js');
const PermissionService = importLazy('../okapi/permissionService.js');

module.exports = async function assignUser(pakeage) {
  const answers = await inquirer.prompt([
    {
      type: 'input',
      name: 'username',
      message: '请输入您的用户名',
    },
    {
      type: 'input',
      name: 'okapiUrl',
      message: '请输入okapiUrl地址',
    },
    {
      type: 'input',
      name: 'tenant',
      message: '请输入租客类型',
    },
  ]);
  const { username, okapiUrl, tenant } = answers;

  const okapi = new Okapi(okapiUrl, tenant);
  const permissionService = new PermissionService(okapi);
  const permissionNames = pakeage.stripes.permissionSets;

  const permissions = [];
  permissionNames.length && permissionNames.map((item) => permissions.push(item.permissionName));

  return permissionService
    .assignPermissionsToUser(permissions, username)
    .then(() => {
      console.log(`User ${username} assigned permission success!!!`);
    })
    .catch((err) => {
      console.log('Error assigning in.', err);
    });
};
